import json
import sys
from PyQt5.QtWidgets import (
    QApplication, QMainWindow, QLabel, QPushButton, QStyleOptionButton, QStyle
)
from PyQt5.QtGui import QPixmap, QFont, QIcon, QPalette, QBrush
from PyQt5.QtCore import Qt

import util
from PicGenerate import generatePic
from content.qianwen import generate_game_content, print_attributes, print_scene_content
from text2speech import generate_and_play_voice
import threading

class TextGameUI(QMainWindow):
    def __init__(self, title, outline, tone):
        super().__init__()
        self.title = title
        self.outline = outline or {}
        self.tone = tone
        self.content_index = 0  # 当前内容索引
        self.game_over = False
        self.chat_history = []
        self.last_choice = None

        self.content = {}
        self.option_buttons = []  # 存储选项按钮
        self.initUI()

    def initUI(self):
        # 窗口设置
        self.setWindowTitle(self.title)
        self.setGeometry(100, 100, 1200, 700)

        # 设置初始背景
        self.original_pixmap = QPixmap('./img/img.png')
        self.original_palette = QPalette()
        self.original_palette.setBrush(QPalette.Window, QBrush(
            self.original_pixmap.scaled(1200, 700, Qt.KeepAspectRatioByExpanding)))
        self.setPalette(self.original_palette)

        # 初始界面 - 游戏标题和梗概
        self.initial_label = QLabel(self)
        self.initial_label.setGeometry(50, 50, 1100, 600)
        self.initial_label.setAlignment(Qt.AlignCenter)
        self.initial_label.setWordWrap(True)  # 启用自动换行
        self.initial_label.setStyleSheet(
            "color: white; font-size: 24px; background-color: rgba(0, 0, 0, 120); padding: 15px; border-radius: 10px;")
        self.initial_label.setText(
            f"<h1>{self.title}</h1>"
            f"<p>{self.outline}</p>"
        )
        self.initial_label.show()

        # 添加右下角提示文本
        self.continue_label = QLabel(self)
        self.continue_label.setGeometry(self.width() - 300, self.height() - 50, 280, 40)  # 右下角位置
        self.continue_label.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.continue_label.setStyleSheet(
            "color: white; font-size: 16px; background-color: transparent; padding: 5px; border-radius: 5px;")
        self.continue_label.setText("点击任意位置继续...")
        self.continue_label.show()

        # 全屏点击区域
        self.start_button = QPushButton("", self)
        self.start_button.setGeometry(0, 0, 1200, 700)
        self.start_button.setStyleSheet("background: transparent;")
        self.start_button.clicked.connect(self.start_game)

        self.show()

    def start_game(self):
        """开始游戏"""
        print("开始游戏")
        self.initial_label.hide()  # 隐藏初始界面
        self.start_button.hide()
        self.continue_label.hide()
        # 顶部按钮（功能菜单）
        self.add_top_button(1020, 20, "img/skip.png")  # 跳过按钮
        self.add_top_button(1080, 20, "img/menu.png")  # 菜单按钮
        self.add_top_button(1140, 20, "img/play.png")  # 播放按钮

        # 半透明遮罩层（用于背景变暗）
        self.dark_overlay = QLabel(self)
        self.dark_overlay.setGeometry(0, 0, 1200, 700)
        self.dark_overlay.setStyleSheet("background-color: rgba(0, 0, 0, 150);")
        self.dark_overlay.hide()  # 初始隐藏

        # 状态栏
        self.status_label = QLabel(self)
        self.status_label.setGeometry(20, 20, 600, 40)
        self.status_label.setStyleSheet("""
                    QLabel {
                        color: white;
                        font-size: 18px;
                        background-color: rgba(0, 0, 0, 150);
                        padding: 10px;
                        border-radius: 5px;
                    }
                """)
        self.status_label.setAlignment(Qt.AlignLeft)
        self.status_label.show()

        self.content = self.get_new_content_based_on_option()
        print("---------- self.content -------")
        print(self.content)

        # 文本区域
        self.text_label = QLabel("", self)
        self.text_label.setGeometry(50, 550, 1100, 120)
        self.text_label.setWordWrap(True)
        self.text_label.setAlignment(Qt.AlignLeft | Qt.AlignTop)
        self.text_label.setStyleSheet(
            "color: white; font-size: 22px; background-color: rgba(0, 0, 0, 120); padding: 15px; border-radius: 10px;")

        # 点击区域
        self.next_button = QPushButton("", self)
        self.next_button.setGeometry(0, 0, 1200, 700)
        self.next_button.setStyleSheet("background: transparent;")
        self.next_button.clicked.connect(self.show_next_content)
        self.next_button.show()
        self.show_next_content()  # 显示第一段内容


    def show_next_content(self):
        print("展示下一段内容")
        """展示下一段内容"""
        # 清理已有选项按钮
        self.clear_options()
        self.dark_overlay.hide()  # 关闭遮罩
        self.text_label.show()  # 显示文本框

        print("self.content_index : ", self.content_index)
        print("len(self.content) : ", len(self.content))
        if self.content_index < len(self.content):
            current = self.content[self.content_index]
            print("current : ", current)
            print("current[type]", current["type"])
            if current["type"] == 1:  # 普通文本
                self.text_label.setText(current["text"])
            elif current["type"] == 2:  # 对话文本
                dialogue = f"{current['name']}：{current['dialogue']}"
                self.text_label.setText(dialogue)
                voice_type = current['voice_type']

                # 这里调用文字转音频的文本
                generate_and_play_voice(
                    text=current['dialogue'],
                    voice=voice_type
                )
                threading.Thread(target=util.sound_play).start()
                # 或许可以右上角加一个音频播放按钮，根据按钮状态控制是否播放

            elif current["type"] == "options":  # 动态选项
                self.text_label.hide()  # 隐藏文本框
                self.dark_overlay.show()  # 显示遮罩层（变暗）
                self.display_options(current["options"])
                self.content_index += 1
                return  # 停止继续增加索引

            self.content_index += 1
        else:
            print("剧情结束！")

    def display_options(self, options):
        """动态显示选项按钮"""
        y_position = 300  # 起始 y 位置
        for option in options:
            # 创建按钮
            button = QPushButton(option["text"], self)
            button.setGeometry(780, y_position, 400, 40)
            button.setStyleSheet("""
                QPushButton {
                    color: white;
                    font-size: 20px;
                    text-align: left;
                    background: transparent;
                    border: none;
                }
                QPushButton:hover {
                    color: #FFD700;
                }
            """)
            # 点击事件绑定
            button.clicked.connect(lambda checked, id=option["id"]: self.handle_option_click(id))
            button.show()
            self.option_buttons.append(button)
            y_position += 50  # 调整下一个按钮的位置

    def clear_options(self):
        """清理选项按钮"""
        for button in self.option_buttons:
            button.deleteLater()
        self.option_buttons.clear()

    def add_top_button(self, x, y, icon_path):
        """顶部功能按钮"""
        button = QPushButton("", self)
        button.setGeometry(x, y, 40, 40)
        button.setIcon(QIcon(icon_path))
        button.setIconSize(button.size())
        button.setStyleSheet("background: transparent; border: none;")
        button.show()

    def update_status_bar(self, health, experience, wealth):
        """更新左上角状态栏"""
        status_text = (
            f"<b>健康值:</b> {health} &nbsp;&nbsp;&nbsp; "
            f"<b>经验值:</b> {experience} &nbsp;&nbsp;&nbsp; "
            f"<b>财富值:</b> {wealth}"
        )
        self.status_label.setText(status_text)

    def handle_option_click(self, option_id):
        """选项按钮点击事件"""
        print(f"你选择了选项ID: {option_id}")
        self.text_label.setText(f"你选择了选项 {option_id}。")
        print(f"你选择了选项ID: {option_id}")
        self.last_choice = option_id

        new_content = self.get_new_content_based_on_option()

        if new_content:
            # 更新内容并重置索引
            self.content = new_content
            self.content_index = 0
            # 清理选项按钮
            self.clear_options()
            # 隐藏遮罩层
            self.dark_overlay.hide()
            # 恢复文本显示
            self.text_label.show()
            # 展示新内容的第一部分
            self.show_next_content()
        else:
            # 如果没有获得新的内容，则显示提示信息
            self.text_label.setText("未能加载新内容，请稍后再试。")

    def get_new_content_based_on_option(self):
        scene_data, new_message = generate_game_content(self.outline, self.tone, self.chat_history, self.last_choice)
        # print("scene_data")
        # 解析返回的数据
        scene_data = json.loads(scene_data)
        is_over = scene_data.get('is_over') == 'true'
        content = scene_data.get('content')
        # print("content : ", content)
        attribute = scene_data.get('attributes')
        health = attribute['health']
        experience = attribute['experience']
        wealth = attribute['wealth']

        options = scene_data.get('options')
        image_prompt = str(scene_data.get('image_prompt'))

        self.update_status_bar(health, experience, wealth)

        #这里生成背景图片
        generatePic(image_prompt)
        new_pixmap = QPixmap('./img/bg.png')  # 使用新的背景图片路径
        new_palette = QPalette()
        new_palette.setBrush(QPalette.Window,
                             QBrush(new_pixmap.scaled(1200, 700, Qt.KeepAspectRatioByExpanding)))
        self.setPalette(new_palette)

        # 打印用户属性
        # print_attributes(attribute)
        # 打印场景内容
        # print_scene_content(content)
        # print("可选选项:")
        # for option in options:
        #     print(option['id'], option['text'])

        # 更新聊天历史
        self.chat_history.append(new_message)
        # print(self.chat_history)

        self.game_over = is_over
        if not self.game_over:
            content = util.convert_content(content, options)
        else:
            # 这里添加跳转到结束的界面
            pass
        return content


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = TextGameUI(title="污名", outline="你是一名孤儿，凭借自身努力考入了知名大学的商学院，毕业后进入一家金融公司工作。就在你准备一展长才之时，却受到一项金融罪名的指控，面临牢狱之灾。即使可以在五天内交齐上千万的保释金，也只是暂时赎回自由。实际上你从未做错任何事，只是被上级推出来成为替罪羊，而公司毫无疑问地放弃了没", tone="")
    sys.exit(app.exec_())